using NUnit.Framework;
using dnAnalytics.LinearAlgebra;
using dnAnalytics.LinearAlgebra.Solvers.Preconditioners;

namespace dnAnalytics.UnitTests.LinearAlgebra.Solvers.Preconditioners
{
    [TestFixture]
    [Category("Managed")]
    public sealed class IncompleteLUFactorizationTest : PreconditionerTest
    {
        internal override IPreconditioner CreatePreconditioner(SparseMatrix matrix)
        {
            return new IncompleteLUFactorization(matrix);
        }

        protected override void CheckResult(IPreconditioner preconditioner, Vector vector, Vector result)
        {
            Assert.AreEqual(typeof(IncompleteLUFactorization), preconditioner.GetType(), "#01");

            IncompleteLUFactorization factorization = preconditioner as IncompleteLUFactorization;
            // Get the Upper triangular matrix U
            // Get the Lower triangular matrix L
            // Get the diagonal matrix D
            // M = (L * U)
            // Compute M * result = product
            // compare vector and product. Should be equal
            Matrix l = factorization.LowerTriagonalMatrix();
            Matrix u = factorization.UpperTriagonalMatrix();

            Matrix matrix = l.Multiply(u);

            Vector product = VectorBuilder.CreateVector(result.Count, VectorType.Dense);
            matrix.Multiply(result, product);

            for (int i = 0; i < product.Count; i++)
            {
                Assert.AreEqual(vector[i], product[i], epsilon, "#02-" + i.ToString());
            }
        }

        [Test]
        public void CompareWithOriginalDenseMatrix()
        {
            SparseMatrix sparseMatrix = (SparseMatrix)MatrixBuilder.CreateMatrix(3, MatrixType.Sparse);
            sparseMatrix[0, 0] = -1;
            sparseMatrix[0, 1] = 5;
            sparseMatrix[0, 2] = 6;
            sparseMatrix[1, 0] = 3;
            sparseMatrix[1, 1] = -6;
            sparseMatrix[1, 2] = 1;
            sparseMatrix[2, 0] = 6;
            sparseMatrix[2, 1] = 8;
            sparseMatrix[2, 2] = 9;
            IncompleteLUFactorization ilu = new IncompleteLUFactorization(sparseMatrix);
            ilu.CreatePreconditioner();
            SparseMatrix original = ilu.LowerTriagonalMatrix().Multiply(ilu.UpperTriagonalMatrix()) as SparseMatrix;

            for (int i = 0; i < sparseMatrix.Rows; i++)
            {
                for (int j = 0; j < sparseMatrix.Columns; j++)
                {
                    Assert.AreEqual(sparseMatrix[i, j], original[i, j], epsilon, "#01-" + i.ToString() + "-" + j.ToString());
                }
            }
        }
    }
}